import { http } from 'utils';
export const getChannels = () => {
  return async (dispatch) => {
    const res = await http.get('/channels');
    const { channels } = res.data.data;
    dispatch({
      type: 'article/getChannels',
      payload: channels,
    });
  };
};
export const getArticles = (params) => {
  return async (dispatch) => {
    const res = await http.get('mp/articles', {
      params,
    });
    const {
      page,
      per_page: pageSize,
      results: list,
      total_count: count,
    } = res.data.data;
    dispatch({
      type: 'article/getArticles',
      payload: {
        // 将数据格式化成 Table 需要的格式
        list: list.map((item) => {
          return {
            ...item,
            cover: item.cover.images[0],
          };
        }),
        count,
        page,
        pageSize,
      },
    });
  };
};
export const deleteArticle = (id, params) => {
  return async (dispatch) => {
    await http.delete(`/mp/articles/${id}`);
    // 继续分发异步 action，获取最新的文章列表数据
    dispatch(getArticles(params));
  };
};
export const updateArticle = (data, draft, isEdit) => {
  return async () => {
    if (isEdit) {
      await http.put(
        `/mp/articles/${data.id}?draft=${draft ? 'false' : 'true'}`,
        data
      );
    } else {
      // 发布
      await http.post(`/mp/articles?draft=${draft ? 'false' : 'true'}`, data);
    }
  };
};
